// GET 抓取自：哔哩哔哩 - 动态首页 - 图片上传
// const API_FILE_UPLOAD = "https://api.vc.bilibili.com/api/v1/drawImage/upload";
const API_FILE_UPLOAD = "https://api.bilibili.com/x/dynamic/feed/draw/upload_bfs";

const API_STATUS_TRUE = 1; // API请求成功，结果为真
const API_STATUS_FALSE = 0; // API请求成功，结果为假
const API_STATUS_ERR_PARAS = -1; // 参数错误
const API_STATUS_ERR_CALL = -2; // API请求失败

function api_file_upload(form_data, callback, callback_progress) {
  if (!form_data) {
    callback({status: API_STATUS_ERR_PARAS, data: null});
    return;
  }

  $.ajax({
    method: "POST",
    url: API_FILE_UPLOAD,
    data: form_data,
    contentType: false,
    processData: false,
    async: true,
    xhr: function () {
      let xhr = new XMLHttpRequest();
      xhr.upload.addEventListener("progress", function (e) {
        if (e.lengthComputable) {
          callback_progress(e.loaded / e.total);
        }
      }, false);
      return xhr;
    }
  }).done(res => {
    if (res["code"] == 0) {
      callback({
        status: API_STATUS_TRUE,
        data: {
          url: res["data"]["image_url"].replace("http://", "https://"),
          width: res["data"]["image_width"],
          height: res["data"]["image_height"]
        }
      });
    } else {
      callback({status: API_STATUS_FALSE, data: null});
    }
  }).fail((jqXHR, textStatus, errorThrown) => {
    console.log(errorThrown);
    callback({status: API_STATUS_ERR_CALL, data: null});
  });
}